package com.itstyle.seckill.distributedlock.redis;


import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.redisson.Redisson;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public class RedissonPerformanceTest {
    private static int TOTAL_PRE_THREADS = 10;
    private static long SECONDS = 10;
    protected static boolean isSkipLock = false;
    private static AtomicInteger flag = new AtomicInteger();
    private static AtomicInteger fail = new AtomicInteger();
    private static AtomicInteger unlock = new AtomicInteger();

    public static void main(String[] args) {
        LoggerContext loggerContext= (LoggerContext) LoggerFactory.getILoggerFactory();
        List<Logger> loggerList = loggerContext.getLoggerList();
        for(Logger logger : loggerList){
            logger.setLevel(Level.ERROR);
        }
        Config config = new Config();
        // for single server
        config.useSingleServer()
                .setAddress("redis://127.0.0.1:6379")
                .setPassword("123456");
        final RedissonClient redissonCli = Redisson.create(config);

        final RLock lock = null;
        final CountDownLatch startLatch = new CountDownLatch(1);
        final CountDownLatch endLatch = new CountDownLatch(TOTAL_PRE_THREADS);
        Thread[]  threads = new Thread[TOTAL_PRE_THREADS];
        setZero(redissonCli);

        for (int i = 0; i < TOTAL_PRE_THREADS; i++) {
            PerformanceThread runningThread = new PerformanceThread(startLatch,endLatch,lock,redissonCli);
            runningThread.start();
            threads[i]=runningThread;
        }

        System.out.println("startLatch countDown");
        //开始执行
        startLatch.countDown();
        try {
            Thread.sleep(SECONDS*1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        System.out.println("startLatch stopThread");

        for (int i = 0; i < threads.length; i++) {
            PerformanceThread runningThread =(PerformanceThread)threads[i];
            runningThread.stopThrad();
        }


        System.out.println("endLatch await");
        try {
            endLatch.await();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        printCount(redissonCli);
        redissonCli.shutdown();
    }


    public static class PerformanceThread extends Thread{
        private volatile boolean isRunning = true;
        private CountDownLatch startLatch ;
        private CountDownLatch endLatch;
        private RLock lock;
        private RedissonClient redissonCli;
        private PerformanceThread(CountDownLatch startLatch ,CountDownLatch endLatch,RLock lock ,RedissonClient redissonCli){
            this.startLatch = startLatch;
            this.endLatch = endLatch;
            this.lock = lock;
            this.redissonCli =redissonCli;
        }

        @Override
        public void run() {
            try {
                System.out.println("startLatch await");
                startLatch.await();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }

            while (isRunning) {
                try {
                    if (!isSkipLock) {
                        lock = redissonCli.getLock("testLock");
                        boolean a= lock.tryLock(3,10, TimeUnit.SECONDS);
                        if(!a) {
                            fail.getAndIncrement();
                            System.out.println("lock fail");
                        }
                    }
                    testUpdate(redissonCli);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (!isSkipLock && lock!=null& lock.isHeldByCurrentThread()) {
                            unlock.getAndIncrement();
                            lock.unlock();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            endLatch.countDown();
        }

        public void stopThrad(){
            isRunning = false;
        }
    }

    /** * 更新对应的记录 */
    public static void testUpdate(RedissonClient redissonCli) {
        RAtomicLong addLong = redissonCli.getAtomicLong("test_performance");
        long totalUsed = addLong.addAndGet(1);
        flag.getAndIncrement();
    }

    /** * 最后获得总数 * @param redissonCli */
    public static void printCount(RedissonClient redissonCli){
        RAtomicLong addLong = redissonCli.getAtomicLong("test_performance");
        System.out.println("count tps is:"+(addLong.get()/SECONDS));
        System.out.println("count update is:"+flag);
        System.out.println("fail lock is:"+fail);
        System.out.println("unlock is:"+unlock);
    }

    /** * 初始化 * @param redissonCli */
    public static void setZero(RedissonClient redissonCli){
        RAtomicLong addLong = redissonCli.getAtomicLong("test_performance");
        addLong.set(0);
    }
}
